package cn.ctyun.ipush.quartz;

import cn.ctyun.ipush.event.ToolSpring;
import cn.ctyun.ipush.model.*;
import cn.ctyun.ipush.service.TaskService;
import cn.ctyun.ipush.service.YixinTokenService;
import cn.ctyun.ipush.utils.*;
import cn.ctyun.ipush.vo.ScheduleJobVo;
import cn.ctyun.ipush.vo.TaskVo;
import cn.ctyun.ipush.web.user.bo.UserModel;
import com.aspose.cells.*;
import com.dexcoder.commons.utils.UUIDUtils;
import com.dexcoder.dal.JdbcDao;
import org.apache.commons.lang.StringUtils;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.awt.image.BufImgSurfaceData;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;

/**
 * 任务工厂类,非同步
 * <p/>
 * User: liyd
 * Date: 14-1-3
 * Time: 上午10:11
 */
@DisallowConcurrentExecution //保证频率高时，同步执行
@PersistJobDataAfterExecution //jobDataMap数据更新支持
public class JobExecutor implements Job {

    /* 日志对象 */
    private static final Logger LOG = LoggerFactory.getLogger(JobExecutor.class);

    public void execute(JobExecutionContext context) throws JobExecutionException {

        Long startTime = System.currentTimeMillis();
        JdbcDao jdbcDao = (JdbcDao) ToolSpring.getApplicationContext().getBean("jdbcDao");
        TaskVo taskVo = null;
        ScheduleJobVo scheduleJobVo=null;
        String currentTrigger =null;
        try {
            //得到job参数
            scheduleJobVo = (ScheduleJobVo) context.getMergedJobDataMap().get(ScheduleJobVo.JOB_PARAM_SCHEDULEJOBVO);
            currentTrigger = context.getTrigger().getKey().getName();

            //spring 得到 taskService
            TaskService taskService = (TaskService) ToolSpring.getApplicationContext().getBean("taskService");

            taskVo = taskService.getTaskVoByTaskId(scheduleJobVo.getTaskId());

            LOG.info(String.format("--- JobTask start execute : jobGroup: %s ,jobName: %s,TriggerTime: %s ,start Time: %s---------- ", scheduleJobVo.getJobGroup(), scheduleJobVo.getJobName(), currentTrigger, DateUtils.timestampToDataString(System.currentTimeMillis())));

            //将数据库数据灌入到Excel模板中，并生成Excel文件
            LOG.info("Excel 文件生成开始");
            ExcelModel excelModel=new ExcelModel();

            WorkbookDesigner workbookDesigner = DataUtils.DBDataToExcelByExcelSql(scheduleJobVo, taskVo, currentTrigger,excelModel,LOG);
            if (null == workbookDesigner) {
                LOG.error("Excel 文件生成失败");
                DataUtils.exceptionDo(jdbcDao, taskVo, scheduleJobVo, currentTrigger,"Excel 文件生成失败");
            } else {
                LOG.info("Excel 文件生成结束");
            }

            //将Excel文件按指定要求生成照片
            LOG.info("workSheet转换图片开始");
            PictureModel pictureModel=taskVo.getPicture();
            Map<String, String> picAndExcelMap = DataUtils.WorkSheetToPicture(scheduleJobVo, workbookDesigner,pictureModel,LOG);
            picAndExcelMap.put("excel",excelModel.getExcelPath());
            if (null == picAndExcelMap) {
                LOG.info("workSheet转换图片失败");
                DataUtils.exceptionDo(jdbcDao, taskVo, scheduleJobVo, currentTrigger,"workSheet转换图片失败");
            } else {
                LOG.info("workSheet转换图片完成");
            }

            //发送邮件
            if(taskVo.getIsSendEmail().equals("1")){
                try {
                    LOG.info("邮件发送开始");
                    boolean isSend=true;
                    String picPathList = picAndExcelMap.get("picture");
                    String excelPaht = picAndExcelMap.get("excel");
                    EmailModel emailModel = taskVo.getEmail();
                    //v1.1
                     emailModel.setEmailContent(taskVo.getEmailContent());
                     emailModel.setEmailSubject(taskVo.getEmailSubject());
                    //v1.1
                    if(taskVo.getIsSendExcel().equals("1") && taskVo.getIsSendPicture().equals("1")){
                        emailModel.setAttachmentList(excelPaht + "$" + picPathList);
                    }else if(taskVo.getIsSendExcel().equals("1") && taskVo.getIsSendPicture().equals("0")){
                        emailModel.setAttachmentList(excelPaht);
                    }else if(taskVo.getIsSendExcel().equals("0") && taskVo.getIsSendPicture().equals("1")){
                        emailModel.setAttachmentList(picPathList);
                    }else{
                        isSend=false;
                    }
                    if(isSend){
                        if(!EmailUtils.startMailSendTask(emailModel)){
                            LOG.error("邮件发送失败，请检查邮件参数是否正确");
                            DataUtils.exceptionDo(jdbcDao, taskVo, scheduleJobVo, currentTrigger,"邮件发送失败，请检查邮件参数是否正确");
                        }
                    }else{
                        LOG.info("邮件发送内容 设置为 EXCEL和图片都不发送！！！");
                    }
                    LOG.info("邮件发送结束");
                } catch (Exception e) {
                    LOG.error("邮件发送失败，错误消息：" + e.getMessage());
                    DataUtils.exceptionDo(jdbcDao, taskVo, scheduleJobVo, currentTrigger,"邮件发送失败，错误消息：" + e.getMessage());
                }
            }else{
                LOG.info("邮件设置为 不发送邮件");
            }

            //发送易信
            if(taskVo.getIsSendYixin().equals("1")){
//                UserModel userModel=new UserModel();
//                userModel.setUserModelId(taskVo.getTaskDetail().getCreateUserid());
//                userModel=jdbcDao.querySingleResult(userModel);
//                String nick = "王俊飞";
//                if(userModel!=null){
//                    nick=userModel.getNick();
//                }
                List<String> nicks = new ArrayList<String>();
                for(String nick:taskVo.getYixinReceivers().split(",")){
                    nicks.add(nick);
                }
                List<String> imgs=new ArrayList<String>();
                //String img = "http://e.hiphotos.baidu.com/exp/w=480/sign=b70c5ab516ce36d3a20482380af23a24/7aec54e736d12f2e5581080f4cc2d562843568dd.jpg";
                //String url = "http://e.hiphotos.baidu.com/exp/w=480/sign=b70c5ab516ce36d3a20482380af23a24/7aec54e736d12f2e5581080f4cc2d562843568dd.jpg";
                //imgs.add(img);
                String title="IPUSH推送图片";
                LOG.info("易信开始发送");
                for(String picYixinUrl:picAndExcelMap.get("pictureYixinURL").split("\\$")){
                    imgs.add(picYixinUrl);
                }
                DataUtils.sendYixinToFriends(nicks, imgs, imgs, title,LOG);
                LOG.info("易信结束发送");
            }else{
                LOG.info("易信设置为 不进行易信发送！！！");
            }
            long endTime = System.currentTimeMillis();
            LOG.info(String.format("--- JobTask end execute : jobGroup: %s ,jobName: %s,TriggerTime: %s ,cost time: %s msec---------- ", scheduleJobVo.getJobGroup(), scheduleJobVo.getJobName(), currentTrigger, endTime - startTime));
        } catch (Exception ex) {
            LOG.error(ex.getMessage());
            DataUtils.exceptionDo(jdbcDao, taskVo, scheduleJobVo, currentTrigger,"JOB执行失败，错误消息：" +ex.getMessage());
        }
    }


//    //发送易信到好友
//    private Boolean sendYixinToFriends(List<String> nicks,List<String> imgs, List<String> urls, String title) {
//        try{
//            YixinTokenService yixinTokenService = (YixinTokenService) ToolSpring.getApplicationContext().getBean("yixinTokenService");
//            YixinTokenModel yixinTokenModel = yixinTokenService.querySingleResult("100");
//            YixinUtils yixinUtils = new YixinUtils();
//            if(yixinUtils.initYixinToken(yixinTokenModel)){
//                yixinTokenService.update(yixinUtils.yixinTokenModelStatic);
//            }
//            for(String img:imgs){
//                yixinUtils.send(nicks, img, img, title, yixinTokenModel);
//            }
//        }catch (Exception ex){
//            LOG.error("易信发送失败："+ex.getMessage());
//            return false;
//        }
//        return false;
//    }
//
//    //处理JOB异常
//    private void exceptionDo(JdbcDao jdbcDao, TaskVo taskVo, ScheduleJobVo scheduleJobVo, String currentTrigger,String message) throws JobExecutionException {
//        JobExecutionException jobExecutionException = new JobExecutionException(new Exception());
//        // 设置 将自动 去除 这个任务的触发器,所以这个任务不会再执行
//        jobExecutionException.setUnscheduleAllTriggers(true);
//        //逻辑处理
//        ///作业状态变化
//        TaskDetailModel taskDetailModel = new TaskDetailModel();
//        taskDetailModel.setTaskDetailModelId(taskVo.getTaskDetail().getTaskDetailModelId());
//        taskDetailModel.setTaskStatus("999");
//        jdbcDao.update(taskDetailModel);
//        ///写到日志表
//        LogModel logModel = new LogModel();
//        logModel.setLogModelId(UUIDUtils.getUUID32());
//        logModel.setLogCreateDate(DateUtils.dateToString(new Date()));
//        logModel.setLogMessage(message);
//        logModel.setLogName(scheduleJobVo.getJobGroup() + "_" +  taskVo.getTaskDetail().getTaskAliasName() + "_" + currentTrigger);
//        jdbcDao.save(logModel);
//        // 抛出异常
//        throw jobExecutionException;
//    }
//
//    /**
//     * worksheet 转换图片
//     *
//     * @param scheduleJobVo
//     * @param workbookDesigner
//     * @return 返回图片和Excel文件列表
//     */
//    private Map<String, String> WorkSheetToPicture(ScheduleJobVo scheduleJobVo, WorkbookDesigner workbookDesigner,PictureModel pictureModel) {
//        Map<String, String> picAndExcelMap = new HashMap<String, String>();
//        int sheetsCount = workbookDesigner.getWorkbook().getWorksheets().getCount();
//        //picAndExcelMap.put("excel", workbookDesigner.getWorkbook().getFileName());
//
//        ImageOrPrintOptions imageOrPrintOptions = new ImageOrPrintOptions();
//        imageOrPrintOptions.setImageFormat(ImageFormat.getPng());
//        imageOrPrintOptions.setOnePagePerSheet(true);
//        //根据配置设置图片的分辨率
//        if(null!=pictureModel){
//            if(!StringUtils.isEmpty(pictureModel.getPicturePix())){
//                imageOrPrintOptions.setHorizontalResolution(Integer.parseInt(pictureModel.getPicturePix()));
//                imageOrPrintOptions.setVerticalResolution(Integer.parseInt(pictureModel.getPicturePix()));
//            }else{
//                imageOrPrintOptions.setHorizontalResolution(100);
//                imageOrPrintOptions.setVerticalResolution(100);
//            }
//        }else{
//            imageOrPrintOptions.setHorizontalResolution(100);
//            imageOrPrintOptions.setVerticalResolution(100);
//        }
//        //根据设置的sheet页的名称，进行相应的图片处理
////        StringBuffer stringBuffer = new StringBuffer();
////        List<String> sheetList=new ArrayList<String>();
////        if(null!=pictureModel){
////            if(!StringUtils.isEmpty(pictureModel.getPicSheetNames())){
////                for(String sheetName:pictureModel.getPicSheetNames().split("\\$")){
////                    sheetList.add(sheetName);
////                }
////                for (int i = 0; i < sheetsCount; i++) {
////                    Worksheet worksheet = workbookDesigner.getWorkbook().getWorksheets().get(i);
////                    worksheet.getPageSetup().setLeftMargin(0.0);
////                    worksheet.getPageSetup().setRightMargin(0.0);
////                    worksheet.getPageSetup().setBottomMargin(0.0);
////                    worksheet.getPageSetup().setTopMargin(0.0);
////                    try {
////                        SheetRender sheetRender = new SheetRender(worksheet, imageOrPrintOptions);
////                        String jobNameDayPath = ExcelUtils.createFileFolderByGroupAndJobName(scheduleJobVo.getJobGroup(), scheduleJobVo.getJobName());
////                        String picPath = jobNameDayPath + "/" + DateUtils.timestampToDataString(System.currentTimeMillis()) + "_" + worksheet.getName() + ".png";
////                        stringBuffer.append(picPath + "$");
////                        sheetRender.toImage(0, picPath);
////                    } catch (Exception e) {
////                        LOG.info(workbookDesigner.getWorkbook().getFileName() + "-" + worksheet.getName() + "转换图片异常");
////                        break;
////                    }
////                }
////
////            }
////        }
//        String sheetNames=pictureModel.getPicSheetNames();
//        if(sheetNames!=null){
//            List<String> sheetList=new ArrayList<String>();
//            if(!StringUtils.isEmpty(sheetNames)){
//                for (String sheetName:sheetNames.split("\\*")){
//                    sheetList.add(sheetName);
//                }
//                StringBuffer stringBuffer = new StringBuffer();
//                StringBuffer yixinPic=new StringBuffer();
//                for (int i = 0; i < sheetsCount; i++) {
//                    Worksheet worksheet = workbookDesigner.getWorkbook().getWorksheets().get(i);
//                    if(sheetList.contains(worksheet.getName())){
//                        worksheet.getPageSetup().setLeftMargin(0.0);
//                        worksheet.getPageSetup().setRightMargin(0.0);
//                        worksheet.getPageSetup().setBottomMargin(0.0);
//                        worksheet.getPageSetup().setTopMargin(0.0);
//                        try {
//                            SheetRender sheetRender = new SheetRender(worksheet, imageOrPrintOptions);
//                            String jobNameDayPath = ExcelUtils.createFileFolderByGroupAndJobName(scheduleJobVo.getJobGroup(), scheduleJobVo.getJobName());
//                            String picPath = jobNameDayPath + "/" + DateUtils.timestampToDataString(System.currentTimeMillis()) + "_" + worksheet.getName() + ".png";
//                            stringBuffer.append(picPath + "$");
//                            sheetRender.toImage(0, picPath);
//
//                            //将图片放在webapp下
//                            LOG.info("图片放在webapp下开始");
//                            String picServerPath=ConfigUtils.getStringValue("pictureServerAddress")+"/" + DateUtils.timestampToDataString(System.currentTimeMillis()) + "_" + worksheet.getName() + ".png";
//                            String picYixinPath=ConfigUtils.getStringValue("pictureYixinURL")+"/" + DateUtils.timestampToDataString(System.currentTimeMillis()) + "_" + worksheet.getName() + ".png";
//                            sheetRender.toImage(0, picServerPath);
//                            yixinPic.append(picYixinPath+"$");
//                            LOG.info("图片放在webapp下结束");
//
//                            LOG.info("转换的sheet页的名称是："+worksheet.getName());
//                        } catch (Exception e) {
//                            LOG.info(workbookDesigner.getWorkbook().getFileName() + "-" + worksheet.getName() + "转换图片异常");
//                            break;
//                        }
//                    }
//                    continue;
//
//                }
//
//
//                if (yixinPic.length() > 0) {
//                    yixinPic.deleteCharAt(yixinPic.length() - 1);
//                    picAndExcelMap.put("pictureYixinURL", yixinPic.toString());
//                } else {
//                    return null;
//                }
//
//                if (stringBuffer.length() > 0) {
//                    stringBuffer.deleteCharAt(stringBuffer.length() - 1);
//                    picAndExcelMap.put("picture", stringBuffer.toString());
//
//                    return picAndExcelMap;
//                } else {
//                    return null;
//                }
//
//
//            }
//        }
//        LOG.error("没有选择要转换图片的sheet页名称！！！");
//        return null;
//
//    }
//
//    /**
//     * 数据源灌入到excel文件
//     *
//     * @param scheduleJobVo
//     * @param taskVo
//     * @param currentTrigger
//     * @return
//     */
//    private WorkbookDesigner DBDataToExcel(ScheduleJobVo scheduleJobVo, TaskVo taskVo, String currentTrigger,ExcelModel excelModel) {
//        Connection conn = null;
//        String userName = taskVo.getDataSource().getUserName();
//        String password = taskVo.getDataSource().getDsPassword();
//        String url = taskVo.getDataSource().getDataSourceUrl();
//        String jobGroup = scheduleJobVo.getJobGroup();
//        String jobName = scheduleJobVo.getJobName(); // todo 替换下面
//
//        List<Map<String, Object>> rsAndPsList = new ArrayList<Map<String, Object>>();
//        try {
//            conn = DBUtils.getTmpConnection(url, userName, password, jobGroup, jobName, currentTrigger);
//            if (null == conn) {
//                LOG.info("Error:  conn create fail");
//                return null;
//            }
//            //得到表集合
//            String tableStr = taskVo.getDataSource().getSqlListDb();
//            List<String> tableList = new ArrayList<String>();
//            if (tableStr != null) {
//                String[] tmpTableList = tableStr.split("\\$");
//                for (String table : tmpTableList) {
//                    tableList.add(table);
//                }
//            } else {
//                LOG.info("table params is empty");
//                return null;
//            }
//
//            //得到table对应的数据集合
//            if (tableList.size() > 0) {
//                for (String table : tableList) {
//                    Map<String, Object> rsMap = DBUtils.executeSelectByTable(conn, table); // return {"ps":psmt,"rs":rs,"tableName":tableName,"sql":sql}
//                    rsAndPsList.add(rsMap);
//                }
//            } else {
//                LOG.error("data generate fail");
//                return null;
//            }
//
//            //得到workDesiger
//            Map<String, ResultSet> rsMap = new HashMap<String, ResultSet>();
//            if (rsAndPsList.size() > 0) {
//                //存放Excel模板的位置
//                String TEMPLATE_FILE_PATH_PART = "excel/Book1.xlsx";//todo 换成变量
//                TEMPLATE_FILE_PATH_PART = taskVo.getExcel().getExcelPath();
//                if (StringUtils.isEmpty(TEMPLATE_FILE_PATH_PART)) {
//                    LOG.error("模板文件地址：TEMPLATE_FILE_PATH_PART 是空的");
//                    return null;
//                }
//                for (Map<String, Object> map : rsAndPsList) {
//                    rsMap.put((String) map.get("tableName"), (ResultSet) map.get("rs"));
//                }
//                String jobNameDayPath = ExcelUtils.createFileFolderByGroupAndJobName(jobGroup, jobName);
//                WorkbookDesigner workbookDesigner = ExcelUtils.dbDataToExcelWithMulTables(rsMap, TEMPLATE_FILE_PATH_PART, jobNameDayPath,excelModel);
//
//
//                LOG.info("Excel 文件生成成功");
//                return workbookDesigner;
//            } else {
//                LOG.error("result data is empty");
//                return null;
//            }
//
//        } catch (Exception ex) {
//            LOG.error(ex.getMessage());
//            return null;
//        } finally {
//            //释放执行statement and resultSet
//            try {
//                for (Map<String, Object> entry : rsAndPsList) {
//                    ResultSet tmprs = (ResultSet) entry.get("rs");
//                    if (tmprs != null && !tmprs.isClosed()) {
//                        tmprs.close();
//                        LOG.info("---ResutlSet has closed ");
//                    }
//                    java.sql.PreparedStatement preparedStatement = (java.sql.PreparedStatement) entry.get("ps");
//                    if (preparedStatement != null && !preparedStatement.isClosed()) {
//                        preparedStatement.close();
//                        LOG.info("---OraclePreparedStatement has closed ");
//                    }
//                }
//            } catch (SQLException e) {
//                LOG.error("ERROR SQL statment execute fail，message：" + e.getMessage());
//            }
//            //释放连接conn
//            try {
//                if (conn != null && !conn.isClosed()) {
//                    conn.close();
//                    LOG.info("---Connection  has closed ");
//                }
//            } catch (SQLException e) {
//                LOG.error("---ERROR: tmp connection fail,message:" + e.getMessage());
//            }
//        }
//    }
}
